#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see http://www.gnu.org/licenses/.

# These lines are only needed if you don't put the script directly into
# the installation directory


import inkex
from inkex.localization import inkex_gettext as _
from inkex.utils import NSS
from lxml import etree

NSS[u"jessyink"] = u"https://launchpad.net/jessyink"
NSS[u"xlink"] = "http://www.w3.org/1999/xlink"

class JessyinkEffects(inkex.EffectExtension):
    def add_arguments(self, pars):
        pars.add_argument('--tab')
        pars.add_argument('--actiontype', type=str, default='none')
        pars.add_argument('--duration', type=str, default='0')
        pars.add_argument('--distance', type=str, default='0')
        pars.add_argument('--pathid', type=str, default='0')

    def effect(self):
        # Check version.
        #scriptNodes = self.document.xpath("//svg:script[@jessyink:version='1.5.6']", namespaces=inkex.NSS)
        #if len(scriptNodes) != 1:
        #   inkex.errormsg(_(u"JessyInk_c 还未安装到这个SVG文件，或者版本不同. 请使用 “扩展” 菜单下 “JessyInk_c” 的 “安装/升级...” 命令进行JessyInk_c 的安装。\n\n"))

        if len(self.svg.selected) == 0:
            raise inkex.AbortExtension(_(u"进行设置前，请先选择一个对象。\n"))
        p_id = self.options.pathid
        #p_id_flag = False
        dur = self.options.duration + "s"
        #if len(self.selected) < -1 and  (self.options.actiontype == "path"):
        #   for id, node in list(self.selected.items()):
        #       if node.tag == inkex.addNS("path", "svg"):
        #           p_id = id
        #           p_id_flag = True
        #           break


        for id, node in list(self.svg.selected.items()):
            # Remove possible action.
            if "onmouseout" in node.attrib:
                del node.attrib["onmouseout"]
            if "onmouseover" in node.attrib:
                del node.attrib["onmouseover"]
            node.set("onmouseout","this.ownerSVGElement.pauseAnimations()")
            node.set("onmouseover","this.ownerSVGElement.unpauseAnimations()")
            if (self.options.actiontype == "rotate"):
                # Create new animateTransform node.
                animateElm = etree.Element(inkex.addNS("animateTransform", "svg"))
                #animateElm.text = "t"
                x = float(node.attrib["x"])
                y = float(node.attrib["y"])
                w = float(node.attrib["width"])
                h = float(node.attrib["height"])
                cx = x + w/2
                cy = y + h/2
                animateElm.set("attributeName", "transform")
                animateElm.set("attributeType", "XML")
                animateElm.set("type", "rotate")
                animateElm.set("note", "translate-tx-ty8scale-sx-sy8rotate-angle-cx-cy8skewX8skewY-angle")
                animateElm.set("values", "0 %.5f %.5f; 360 %.5f %.5f" % (cx, cy, cx, cy))
                animateElm.set("begin", "mousedown")
                #animateElm.set("end", "mouseout")
                animateElm.set("begin_b", "0s")
                animateElm.set("dur", dur)
                animateElm.set("repeatCount", "indefinite")
                #animateElm.set("accumulate", "sum")
                animateElm.set("additive", "sum")
                # Remove old animateTransform.
                #for nmm in node.getchildren():
                #   if nmm.tag == inkex.addNS('animateTransform','svg'):
                #       node.remove(nmm)
                node.append(animateElm)

            if (self.options.actiontype == "move"):
                # Create new animateTransform node.
                animateElm = etree.Element(inkex.addNS("animate", "svg"))
                animateElm.set("attributeName", "x")
                #animateElm.set("from", "0")
                #animateElm.set("to", "95")
                animateElm.set("by", self.options.distance)
                animateElm.set("fill", "freeze")
                animateElm.set("attributeType", "XML")
                animateElm.set("begin", "mousedown")
                #animateElm.set("end", "mouseout")
                animateElm.set("begin_b", "0s")
                animateElm.set("dur", dur)
                animateElm.set("repeatCount", "indefinite")
                node.append(animateElm)
                # Create new animateTransform node.
                animateElm = etree.Element(inkex.addNS("animate", "svg"))
                animateElm.set("attributeName", "y")
                #animateElm.set("from", "0")
                #animateElm.set("to", "95")
                animateElm.set("by", self.options.distance)
                animateElm.set("fill", "freeze")
                animateElm.set("attributeType", "XML")
                animateElm.set("begin", "mousedown")
                #animateElm.set("end", "mouseout")
                animateElm.set("begin_b", "0s")
                animateElm.set("dur", dur)
                animateElm.set("repeatCount", "indefinite")
                #animateElm.set("accumulate", "sum")
                animateElm.set("additive", "sum")
                node.append(animateElm)
            #   node.set("onclick","jumpto(" + self.options.jumpslide + "," + self.options.jumpeffect + ")")

                #if node.tag == inkex.addNS("path", "svg") and p_id_flag == True:
                    #p_id_flag = False
                    #continue
            if (self.options.actiontype == "path"):
                if len(p_id) < 1:
                    raise inkex.AbortExtension(_(u"需要填写运动轨迹路径的ID。\n"))
                    break
                # Create new animateMotion node.
                animateElm = etree.Element(inkex.addNS("animateMotion", "svg"))
                animateElm.set("dur", "0s")
                animateElm.set("begin", "0s")
                animateElm.set("rotate", "auto")
                animateElm.set("fill", "remove")
                pathElm = etree.Element(inkex.addNS("mpath", "animateMotion"))
                pathElm.set("{" + NSS[u"xlink"] + "}href", "#" + p_id)
                animateElm.append(pathElm)
                node.append(animateElm)

                animateElm = etree.Element(inkex.addNS("animateMotion", "svg"))
                animateElm.set("dur", dur)
                animateElm.set("repeatCount", "indefinite")
                animateElm.set("rotate", "auto")
                animateElm.set("begin", "mousedown")
                animateElm.set("fill", "freeze")
                #animateElm.set("accumulate", "sum")
                #animateElm.set("additive", "sum")
                #animateElm.set("end", "mouseout")
                pathElm = etree.Element(inkex.addNS("mpath", "animateMotion"))
                pathElm.set("{" + NSS[u"xlink"] + "}href", "#" + p_id)
                animateElm.append(pathElm)
                node.append(animateElm)
                #http://edutechwiki.unige.ch/en/SVG-SMIL_animation_tutorial

# Create effect instance
if __name__ == '__main__':
    JessyinkEffects().run()
